package com.wei.czz.common.easyexcel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.NumberUtils;
import com.alibaba.fastjson2.JSON;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wyw
 * date: 2024-11-24 22:03:06
 * className: CzzLongStringConverter
 * version: 1.0
 * description:
 */
public class CzzLongStringConverter implements Converter<Long> {

    private static final Logger log = LoggerFactory.getLogger(CzzLongStringConverter.class);

    @Override
    public Class<?> supportJavaTypeKey() {
        return Long.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Long convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        if (StringUtils.isNotBlank(cellData.getStringValue())) {
            return NumberUtils.parseLong(cellData.getStringValue(), contentProperty);
        }
        if (Objects.nonNull(cellData.getOriginalNumberValue())) {
            return cellData.getOriginalNumberValue().longValue();
        }
        log.info("原始值解析结果为空。cellData={}", JSON.toJSONString(cellData));
        return null;
    }

    @Override
    public WriteCellData<?> convertToExcelData(Long value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return NumberUtils.formatToCellDataString(value, contentProperty);
    }

}
